package com.example.weatherapp033;

import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.view.GravityCompat;

import com.bumptech.glide.Glide;

import com.example.weatherapp033.databinding.ActivityWeatherBinding;
import com.example.weatherapp033.gson.AQI;
import com.example.weatherapp033.gson.BingPic;
import com.example.weatherapp033.gson.Forecast;
import com.example.weatherapp033.gson.NowWeather;
import com.example.weatherapp033.gson.Suggest;
import com.example.weatherapp033.gson.TotalWeather;
import com.example.weatherapp033.util.HttpUtil;
import com.example.weatherapp033.util.Utility;
import com.google.gson.Gson;

import org.jetbrains.annotations.NotNull;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
import io.reactivex.rxjava3.core.Observable;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class WeatherActivity extends AppCompatActivity {
    ActivityWeatherBinding binding;
    public static final String FORECAST_URL = "https://devapi.qweather.com/v7/weather/7d";
    public static final String AQI_URL = "https://devapi.qweather.com/v7/air/now";
    public static final String SUGGEST_URL = "https://devapi.qweather.com/v7/indices/1d";
    public static final String NOWEATHER_URL = "https://devapi.qweather.com/v7/weather/now";
    public static final String KEY = "48eded087f314b1ea7e68b69f6c121a9";
    private String current_province;
    private String current_city;
    private String current_county;
    private String type = "1,3,8";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (Build.VERSION.SDK_INT >= 21) {
            View decorView = getWindow().getDecorView();
            decorView.setSystemUiVisibility(
                    View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                            | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
            getWindow().setStatusBarColor(Color.TRANSPARENT);
        }
        binding = ActivityWeatherBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());


        loadBingPic();

        Intent intent = getIntent();
        String weatherId = intent.getStringExtra("weather_id");
        current_province = intent.getStringExtra("current_province");
        current_city = intent.getStringExtra("current_city");
        current_county = intent.getStringExtra("current_county");
        binding.includeTitle.titleCity.setText(String.format("%s %s %s", current_province,
                current_city, current_county));

        if (weatherId != null && weatherId.length() > 2) {
            weatherId = weatherId.substring(2); // 去掉CN
            requestWeather(weatherId); // 每次都主动请求
        } else {
            // 如果没有传递weatherId，可以考虑用缓存
            SharedPreferences sp = getSharedPreferences("weather", MODE_PRIVATE);
            String json = sp.getString("weather", "");
            String location = sp.getString("location", "");
            String updateTime=sp.getString("updateTime","");


            if (!TextUtils.isEmpty(json)) {
                Gson gson = new Gson();
                TotalWeather totalWeather = gson.fromJson(json, TotalWeather.class);
                showNowWeatherInfo(totalWeather.getNowWeather());
                showForecastInfo(totalWeather.getForecast());
                showAQIIInfo(totalWeather.getAqi());
                showSuggestInfo(totalWeather.getSuggest());
                binding.includeTitle.titleCity.setText(location);
                binding.includeTitle.titleUpdateTime.setText(updateTime);
                // 在这里添加更新地图的全部代码
            }
        }


    }

    private void loadBingPic() {
        String url = "https://api.xygeng.cn/openapi/bing/";
        HttpUtil.sendOkHttpRequest(url, new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                Toast.makeText(WeatherActivity.this,"获取Bing每日图片失败",
                        Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                String result = response.body().string();
                BingPic bingPic = new Gson().fromJson(result, BingPic.class);
                Log.d("TAG123", result);
                runOnUiThread(() -> {
                    if (bingPic != null && bingPic.getCode() == 200) {
                        //加载图片
                        Glide.with(WeatherActivity.this).
                                load(bingPic.getData().getUrl()).into(binding.bingPicImg);
                    } else {
                        Toast.makeText(WeatherActivity.this, "获取Bing每日图片失败",
                                Toast.LENGTH_SHORT).show();
                    }
                });
            }
        });
    }

    private void loadBingpic() {
        String url = "https://api.xygeng.cn/openapi/bing/";
        HttpUtil.sendOkHttpRequest(url, new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                Toast.makeText(WeatherActivity.this,"获取Bing每日图片失败",
                        Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                String result = response.body().string();
                BingPic bingPic = new Gson().fromJson(result, BingPic.class);
                Log.d("TAG123", result);
                runOnUiThread(() -> {
                    if (bingPic != null && bingPic.getCode() == 200) {
                        //加载图片
                        Glide.with(WeatherActivity.this).
                                load(bingPic.getData().getUrl()).into(binding.bingPicImg);
                    } else {
                        Toast.makeText(WeatherActivity.this, "获取Bing每日图片失败",
                                Toast.LENGTH_SHORT).show();
                    }
                });
            }
        });
    }

    public void requestWeather(String location) {
        loadBingpic();

        String url0 = NOWEATHER_URL + "?" + "location=" + location + "&key=" + KEY;
        String url1 = FORECAST_URL + "?" + "location=" + location + "&key=" + KEY;
        String url2 = AQI_URL + "?" + "location=" + location + "&key=" + KEY;
        String url3 = SUGGEST_URL + "?" + "location=" + location + "&key=" + KEY + "&type=" + type;

        Gson gson=new Gson();

        Observable<Response> observable0 = HttpUtil.request(url0);
        Observable<Response> observable1 = HttpUtil.request(url1);
        Observable<Response> observable2 = HttpUtil.request(url2);
        Observable<Response> observable3 = HttpUtil.request(url3);

        Observable.zip(
                observable0,
                observable1,
                observable2,
                observable3,
                (response0, response1, response2, response3) -> {
                    try {
                        // 假设这里的parseResponse方法可以将响应解析成对应的类
                        NowWeather nowWeather = gson.fromJson(response0.body().string(), NowWeather.class);
                        Forecast forecast = gson.fromJson(response1.body().string(), Forecast.class);
                        AQI aqi = gson.fromJson(response2.body().string(), AQI.class);
                        Suggest suggest = gson.fromJson(response3.body().string(), Suggest.class);

                        TotalWeather totalWeather=new TotalWeather();
                        totalWeather.setNowWeather(nowWeather);
                        totalWeather.setAqi(aqi);
                        totalWeather.setForecast(forecast);
                        totalWeather.setSuggest(suggest);

                        String toWrite = gson.toJson(totalWeather);

                        SharedPreferences sp = getSharedPreferences("weather", MODE_PRIVATE);
                        SharedPreferences.Editor editor = sp.edit();
                        editor.putString("weather",toWrite);
                        SimpleDateFormat sf=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
                        editor.putString("updateTime",sf.format(new Date()));
                        editor.putString("location", String.format("%s %s %s", current_province, current_city, current_county));

                        editor.apply();

                        return new Object[]{nowWeather, forecast, aqi, suggest};
                    } finally {
                        // 记得关闭响应
                        response0.close();
                        response1.close();
                        response2.close();
                        response3.close();
                    }
                }
        ).observeOn(AndroidSchedulers.mainThread())
                .subscribe(
                        results -> {
                            // 在这里处理所有请求的结果
                            // results 是一个包含所有请求结果的数组
                            showNowWeatherInfo((NowWeather)results[0]);
                            showForecastInfo((Forecast)results[1]);
                            showAQIIInfo((AQI)results[2]);
                            showSuggestInfo((Suggest)results[3]);
                        },
                        throwable -> {
                            // 在这里处理异常
                            Toast.makeText(this, "访问网络操作出错！", Toast.LENGTH_SHORT).show();
                        }
                );



    }



    private void showNowWeatherInfo(NowWeather nowWeather) {

        if (nowWeather != null && nowWeather.getCode().equals("200")) {
            String temp = nowWeather.getNow().getTemp();
            binding.includeNow.weatherInfoText.setText(nowWeather.getNow().getText());
            binding.includeNow.degreeText.setText(String.format("%s ℃ ", temp));
        } else {
            Toast.makeText(this, "获取实时天气信息出错！", Toast.LENGTH_SHORT).show();
        }

    }

    private void showSuggestInfo(Suggest suggest) {

        if (suggest != null && suggest.getCode().equals("200")) {
            binding.includeSuggestion.comfortText.setText(String.format("舒适度指数：\n %s \n %s",
                    suggest.getDaily().get(2).getCategory(),
                    suggest.getDaily().get(2).getText()));
            binding.includeSuggestion.sportText.setText(String.format("运动指数：\n %s \n %s",
                    suggest.getDaily().get(0).getCategory(),
                    suggest.getDaily().get(0).getText()));
            binding.includeSuggestion.wearText.setText(String.format("穿衣指数：\n %s \n %s",
                    suggest.getDaily().get(1).getCategory(),
                    suggest.getDaily().get(1).getText()));
        } else {
            Toast.makeText(this, "获取天气指数出错！", Toast.LENGTH_SHORT).show();
        }

    }

    private void showAQIIInfo(AQI aqi) {

        if (aqi != null && aqi.getCode().equals("200")) {
            binding.includeAqi.aqiText.setText(aqi.getNow().getAqi());
            binding.includeAqi.pm25Text.setText(aqi.getNow().getPm2p5());
        } else {
            Toast.makeText(this, "获取实时空气质量出错！", Toast.LENGTH_SHORT).show();
        }

    }
    private void showForecastInfo(Forecast forecast) {

        if (forecast != null && forecast.getCode().equals("200")) {
            binding.includeForecast.forecastLayout.removeAllViews();
            for (Forecast.DailyDTO dailyDTO : forecast.getDaily()) {
                View view = LayoutInflater.from(this).inflate(R.layout.activity_forecast_item,
                        binding.includeForecast.forecastLayout, false);
                TextView dateText = (TextView) view.findViewById(R.id.date_text);
                TextView infoText = (TextView) view.findViewById(R.id.info_text);
                TextView maxText = (TextView) view.findViewById(R.id.max_text);
                TextView minText = (TextView) view.findViewById(R.id.min_text);
                dateText.setText(dailyDTO.getFxDate());
                infoText.setText(dailyDTO.getTextDay());
                maxText.setText(dailyDTO.getTempMax());
                minText.setText(dailyDTO.getTempMin());
                binding.includeForecast.forecastLayout.addView(view);
            }
        } else {
            Toast.makeText(this, "获取未来7天天气预报出错！", Toast.LENGTH_SHORT).show();
        }

    }



}